//<my-matriculator - a simple tool for registering racers in a USAC cyclocross race>
//Copyright (C) <2011>  <Steven Rivers>

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using Registration.Model.Entities;

namespace Registration.Model
{
    class MappingDb
    {
        public static ICollection<Mapping> GetAllMappings()
        {
            var ds = MappingDbDataSet.ReadDataSet();

            var mappings = new ObservableCollection<Mapping>();

            foreach (var f in from DataRow m in ds.Tables["Mapping"].Rows select new Mapping((string)m["RaceName"], (int)m["CategoryId"]))
            {
                mappings.Add(f);
            }
            return mappings;
        }

        public static int GetCategoryIdForRaceName(string racename)
        {
            var maps = GetAllMappings();

            var matches = from m in maps
                          where m.RaceName.ToUpper() == racename.ToUpper()
                          select m.CategoryId;
            
            return matches.FirstOrDefault();
        }

        public static void AddMapping(Mapping map)
        {
            var ds = MappingDbDataSet.ReadDataSet();
            var row = ds.Tables["Mapping"].NewRow();
            row.SetField("RaceName", map.RaceName);
            row.SetField("CategoryId", map.CategoryId);
            ds.Tables["Mapping"].Rows.Add(row);
            MappingDbDataSet.WriteDataSet(ds);
        }
    }
}